
const sequelize = require('../config/operateDB');
const {Sequelize, DataTypes, Op} = require('sequelize');
const {setSession} = require('../utils/utils');
const svgCaptcha = require('svg-captcha');
const { defaultMaxListeners } = require('koa');

const User = sequelize.define('user', {
    id: {
        type: DataTypes.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV4,
    },
    name: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    accountNo: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    password: {
        type: DataTypes.TEXT,
        allowNull: false,
    },
    telNo: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    remark: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    isManager: DataTypes.BOOLEAN,
}, {

})

User.sync();
User.findOne({
    where: {
        accountNo: 'admin'
    },
    raw: true
}).then( res => {
    !res && User.create({
        accountNo: 'admin',
        password: 'admin',
        isManager: true
    })
    res && console.log('已存在超级管理员 账号密码admin');
})

const usersModel = {
    async register(ctx) {
        const params = ctx.query;
        const validText = this.validAccount(ctx, params);
        if (!validText) return ;
        const user = await this.getUser(params);
        if (user) {
            ctx.errorParams('账号重复！');
        } else {
            await User.create({
                ...params,
                name: params.name || params.accountNo,
                telNo: params.telNo || '',
                isManager: false,
            });
            ctx.success('注册成功！', params.accountNo);
        }
        
        
    },

    validAccount(ctx, params) {
        if (!params.accountNo) {
            ctx.errorParams('账号不能为空！');
            return false;
        } else if (!params.password) {
            ctx.errorParams('密码不能为空！');
            return false;
        } else  {
            return true;
        }
    },
    async login(ctx) {
        const params = ctx.request.body;
        const validText = this.validAccount(ctx, params);
        if (!validText) return ;
        const user = await this.getUser(params);
        if (!user || (!!user && user.password !== params.password)) {
            ctx.errorParams('账号或密码错误');
        } 
        // else if (!params.captcha) {
        //     ctx.errorParams('验证码为空！');
        // } else if (params.captcha.toLowerCase() !== ctx.session.captcha) {
        //     ctx.errorParams('验证码错误！');
        // } 
        else {
            setSession(ctx, user);
            ctx.success('登录成功！', user);
        }
    },

    async loginOut(ctx) {
        setSession(ctx, null);
        ctx.success('退出登录成功！');
    },

    async getUser(params) {
        const user = await User.findOne(
            {
                where: {
                    accountNo: params.accountNo
                },
                raw: true,
            }
        );

        return user;
    },
    async getCaptcha(ctx) {
        const cap = svgCaptcha.create({
            size: 4, // 验证码长度
            width:160,
            height:60,
            fontSize: 50,
            ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
            noise: 2, // 干扰线条的数量
            color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
            background: '#eee' // 验证码图片背景颜色
          })
          let img = cap.data // 验证码
          var text = cap.text.toLowerCase() // 验证码字符，忽略大小写
          ctx.session.captcha = text;
          ctx.success('获取验证码成功！', {svg: img});
    },

    async editUser(ctx) {
        const params = ctx.request.body;
        const editId = params.id;
        if (!editId) {
            ctx.errorParams('id不存在！');
        } else {
            // 
            const user = await User.findOne({
                where: {
                    id: editId
                },
                raw: true,
            });
            await User.update({
                ...user,
                ...params,
            }, {
                where: {
                    id: editId
                },
            })
            
            ctx.success('修改成功', {
                id: editId,
            });
        }
    },

    async getUsers(ctx) {
        const params = ctx.query;
        // const count = await Products.count();
        const {offset = 0, limit = 10, keywords = ''} = params;
        const { count, rows } = await User.findAndCountAll(
            {
                where: {
                    name: {
                        [Op.like]: '%' + keywords + '%',
                    },
                },
                limit: parseInt(limit),
                offset: parseInt(offset),
                raw: true,
            }
        );

        ctx.pageRes({
            limit,
            offset,
            list: rows,
            total: count,
        });
    },

    async delUser(ctx) {
        const deleteId = ctx.request.body.id;
        if (!deleteId) {
            ctx.errorParams('id不存在！');
        } else {
            await User.destroy({
                where: {
                    id: deleteId,
                }
            });

            ctx.success('删除成功！', {
                id: deleteId,
            })
        }
    }
};


module.exports = usersModel;